package com.lhd.web;

import com.lhd.po.Blog;
import com.lhd.service.BlogService;
import com.lhd.service.UserService;
import com.lhd.vo.BlogQuery;
import com.lhd.po.Type;
import com.lhd.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by limi on 2017/10/23.
 */
@Controller
public class TypeShowController {

    @Autowired
    private TypeService typeService;

    @Autowired
    private BlogService blogService;

    @Autowired
    private UserService userService;


//    @PostMapping("/admin/type/post")
//    public Integer postType(Integer tid, String tname){
//        System.out.println(tid+tname);
//        return 0;
//    }

    @GetMapping("/types/{id}")
    public String types(@RequestParam(value = "page", required = false, defaultValue = "0") Integer page,
                        @PathVariable Long id, Model model) {


        //列出所有的type
        List<Type> types = typeService.listType();
        //给各个type添加博客数目
        for (Type type:types){
            type.setCount(typeService.countTypeByTypeId(type.getId()));
        }
        //如果id=-1且type数目大于0则激活id为首个
        if (id == -1 && types.size() > 0) {
           id = types.get(0).getId();
        }
        List<Blog> blogs = blogService.listBlogByTypeId(id,page);
        for (Blog b:blogs){
            b.setUser(userService.getUserById(b.getUserId()));
            b.setType(typeService.getType(b.getTypeId()));
        }
        model.addAttribute("types", types);
        model.addAttribute("page", blogs);
        model.addAttribute("activeTypeId", id);


        Long count = Long.valueOf(typeService.countTypeByTypeId(id));
        Integer rem = Math.toIntExact(count % 3);

        model.addAttribute("pageNum",count/3 + (rem == 0 ? 0 : 1));
        model.addAttribute("curPage",page);
        model.addAttribute("preBoolean",page > 0);
        model.addAttribute("nexBoolean",page < ((count/3 + (rem == 0 ? 0 : 1))-1));
        return "types";
    }
}
